import React, { useEffect, useState } from 'react';
import ProForm, { ModalForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-form';
import { Card, Row, Col, Checkbox, Menu } from 'antd';
import { useModel } from 'umi';
import { getAllMenu, getRoleActionList, getDeptList } from '@/services/permissions/api';
import { CheckboxValueType } from 'antd/lib/checkbox/Group';
import './style.less';
import { OptType } from '@/utils/constants';
import { isNull, showMsg } from '@/utils/utils';

const OptForm: React.FC<any> = (props) => {
  const {
    handleVisible,
    handleAdd,
    record = {},
    optType,
    deptList
  } = props;

  const { initialState } = useModel('@@initialState');
  // 菜单数据
  const [menuData, setMenuData] = useState([]);

  // 一级菜单
  const [topMenu, setTopMenu] = useState([]);
  const [topMenuDefaultKey, setTopMenuDefaultKey] = useState<string>('');

  // 二级菜单
  const [subMenu, setSubMenu] = useState([]);
  const [subMenuDefaultKey, setSubMenuDefaultKey] = useState<string>('');

  // 按钮权限列表
  const [actionList, setActionList] = useState<CheckboxValueType[]>([]);

  // 已选择的列表
  const [checkedList, setCheckedList] = useState<CheckboxValueType[]>([]);

  // 全选
  const [checkAll, setCheckAll] = useState<boolean>(false);

  // 全部
  const [allButtonList, setAllButtonList] = useState<CheckboxValueType[]>([])

  const [curDept, setCurDept] = useState();

  useEffect(() => {
    getAllMenu().then(data => {
      setMenuData(data);
      // 一级菜单
      setTopMenu(data);
      setTopMenuDefaultKey(data[0].menu_id);

      // 二级菜单
      setSubMenu(data[0].sub_list);
      setSubMenuDefaultKey(data[0].sub_list[0].sub_menu_id);

      // 权限列表
      const list = data[0].sub_list[0].action_list;
      setActionList(list);
      getBtnList(list);
      //
      if (optType === OptType.ADD) {
        const result = deptList.find(item => item.dept_code === initialState?.currentUser?.dept_code) || {};
        setCurDept({ dept_code: result.dept_code || '', dept_name: result.dept_name || '' })
      } else {
        setCurDept({ dept_code: record.dept_code || '', dept_name: record.dept_name || '' })
      }
    });
  }, []);

  // 获取用户权限
  const getBtnList = (ary) => {
    if (record.role_id) {
      getRoleActionList(record.role_id).then((list: any[]) => {
        if (list && list.length) {
          const buttonList = list.map(item => {
            return item.button_id;
          });
          setCheckedList(buttonList);
          setAllButtonList(buttonList)

          console.log('actionList', ary, buttonList)
          // 设置是否全选
          let allFlag = ary.every(item => {
            return buttonList.indexOf(item.button_id) > -1;
          })
          setCheckAll(allFlag)
        }
      });
    }
  }

  useEffect(() => {
    // 清空
    if (optType === OptType.ADD) {
      setAllButtonList([])
    }
  }, [optType])

  // 一级菜单
  const onTopMenu = (item: any) => {
    const topMenus: any = topMenu.find((menu: any) => menu.menu_id === item.key);
    setSubMenu(() => {
      return topMenus.sub_list
    });

    setTopMenuDefaultKey(item.key);
    setSubMenuDefaultKey(topMenus.sub_list[0].sub_menu_id);
    setActionList(topMenus.sub_list[0].action_list);

    console.log('topMenus', topMenus)
    console.log('allButtonList', allButtonList)
    // 一级菜单的二级列表的权限列表在已添加的权限列表中，设置为全选
    let allFlag = topMenus?.sub_list[0]?.action_list?.every(item => {
      return allButtonList.indexOf(item.button_id) > -1;
    })
    setCheckAll(allFlag)
  }

  // 二级菜单
  const onSubMenu = (item: any) => {
    const action: any = subMenu.find((menu: any) => menu.sub_menu_id === item.key);
    setSubMenuDefaultKey(item.key);
    setActionList(action.action_list);

    console.log('allButtonList', allButtonList)
    // 当前权限列表在已添加的权限列表中，设置为全选
    let allFlag = action.action_list.every(item => {
      return allButtonList.indexOf(item.button_id) > -1
    })
    setCheckAll(allFlag)
  }

  const onChange = (checkedValues: CheckboxValueType[]) => {
    const list = allButtonList.concat([])

    console.log('checkedValues', checkedValues)
    // 全选
    setCheckAll(checkedValues.length === actionList.length)

    // 先移除当前菜单所有项
    actionList.forEach((action: any) => {
      const index = list.indexOf(action.button_id)
      if (index > -1) {
        list.splice(index, 1)
      }
    })

    checkedValues.forEach(item => {
      list.push(item);
    })
    console.log(list);
    setAllButtonList(list)
    setCheckedList(list)
  }

  // 全选
  const onCheckAllChange = (e: any) => {
    // 获取当前菜单下的权限列表
    const list = actionList.map((item: any) => item.button_id);
    const yuanAll = JSON.parse(JSON.stringify(allButtonList));
    console.log('list', list)
    console.log('yuanAll', yuanAll);

    list.forEach((id, key) => {
      const index = yuanAll.findIndex(item => item === id);
      console.log('index', index, key, e.target.checked)
      if (e.target.checked) {
        if (index === -1) {
          yuanAll.push(id)
        }
      } else {
        if (index > -1) {
          yuanAll.splice(index, 1)
        }
      }
    })
    console.log('allButtonList', yuanAll)
    setAllButtonList(yuanAll);
    setCheckedList([].concat(yuanAll));
    setCheckAll(e.target.checked);
  };

  return <ModalForm
    title="新建/编辑角色"
    width="90%"
    visible
    layout="horizontal"
    modalProps={{
      maskClosable: false
    }}
    className="role-dialog"
    onVisibleChange={handleVisible}
    onFinish={async (value) => {
      console.log('value', value, curDept)
      let params = {};
      if (optType !== OptType.EDIT) {
        params = Object.assign({}, record, value, { button_id_list: allButtonList, dept_code: curDept.dept_code, dept_name: curDept.dept_name });
      } else {
        params = Object.assign({}, record, value, { button_id_list: allButtonList });
      }
      console.log('params', params)
      await handleAdd(params as PERMISSIONSAPI.RoleListItem).then(res => {
        if (res) {
          handleVisible(false);
          window.location.reload();
        }
      }).catch((error) => {
        showMsg(error?.data?.errmsg);
      })
    }}
    submitter={{
      searchConfig: {
        resetText: '关闭',
        submitText: '保存'
      }
    }}
  >
    <ProForm.Group>
      <ProFormText
        rules={
          [
            {
              required: true
            }
          ]
        }
        label="角色名称"
        placeholder="请输入角色名称"
        width="md"
        initialValue={record.role_name}
        name="role_name" />
      {/* <ProFormText
          disabled
          initialValue={initialState?.currentUser?.dept_name}
          width="md"
          name="dept_name"
          label="归属科室"/> */}
      {
        (optType === OptType.EDIT || initialState?.currentUser?.identity_type !== 'A')
          ? <ProFormText label="业务科室" name="dept" initialValue={record.dept_name || initialState?.currentUser?.dept_name} required readonly />
          : <ProFormSelect
            label="业务科室"
            width="md"
            rules={
              [
                {
                  required: true
                }
              ]
            }
            name="dept"
            options={deptList.map(item => {
              return {
                label: `${item.dept_code}-${item.dept_name}`,
                value: item.dept_code,
                data: item,
              }
            })}
            // readonly={optType === OptType.EDIT || initialState?.currentUser?.identity_type !== 'A'}
            initialValue={record.dept_code || initialState?.currentUser?.dept_code}
            fieldProps={{
              onSelect: (val, opt) => setCurDept(opt.data),
              showSearch: true,
              filterOption: true,
              placeholder: '请输入或选择'
            }}
          />
      }
    </ProForm.Group>

    <ProForm.Group>
      <ProFormTextArea
        rules={
          [
            {
              required: true
            }
          ]
        }
        label="角色描述"
        placeholder="请输入角色描述"
        width="md"
        initialValue={record.role_desc}
        name="role_desc" />
    </ProForm.Group>

    <div style={{ marginBottom: 10, fontSize: 12 }}>角色权限分配：</div>

    <Row style={{ border: '1PX #eee solid' }}>
      <Col span={8} style={{ borderRight: '1PX #eee solid' }}>
        <Card className="menu-card" bordered={false}>
          <Menu
            selectedKeys={[topMenuDefaultKey]}
            onClick={onTopMenu}>
            {
              menuData && menuData.map((item: any) => {
                return <Menu.Item key={item.menu_id}>{item.menu_name}</Menu.Item>
              })
            }
          </Menu>
        </Card>
      </Col>
      <Col span={8} style={{ borderRight: '1PX #eee solid' }}>
        <Card className="menu-card" bordered={false}>
          <Menu
            selectedKeys={[subMenuDefaultKey]}
            onClick={onSubMenu}>
            {
              subMenu && subMenu.map((item: any, index: number) => {
                return <Menu.Item key={item.sub_menu_id}>{item.sub_menu_name}</Menu.Item>
              })
            }
          </Menu>
        </Card>
      </Col>
      <Col span={8}>
        <Card className="checkbox--card" bordered={false}>
          <div>
            <Checkbox checked={checkAll} onChange={onCheckAllChange}>全选</Checkbox>
          </div>
          <Checkbox.Group onChange={onChange} value={checkedList}>
            <Row>
              {
                actionList && actionList.map((item: any) => {
                  return <Col span={24} key={item.button_id}>
                    <Checkbox value={item.button_id}>{item.button_name}</Checkbox>
                  </Col>
                })
              }
            </Row>
          </Checkbox.Group>
        </Card>
      </Col>
    </Row>

  </ModalForm>
}
export default OptForm;
